package com.gydz.gydzbaseframeworkboot.Common.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
//需具体定义包名 存在多数据源情况
@MapperScan(basePackages = "com.gydz.gydzbaseframeworkboot.SgsE.dao", sqlSessionFactoryRef = "SgsESqlSessionFactory")
public class SgsEConfig {

    @Bean("SgsEDataSource")
    @Qualifier("SgsEDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.sgs-e")
    public DataSource getSgsEDataSource(){
        DruidDataSource datasource = new DruidDataSource();
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

    @Bean("SgsESqlSessionFactory")
    public SqlSessionFactory SgsESqlSessionFactory(@Qualifier("SgsEDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mybaties的mapper.xml所在位置
        //需具体定义到xml文件上一级文件名 存在多数据源情况
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/**/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean("SgsESqlSessionTemplate")
    public SqlSessionTemplate SgsESqlSessionTemplate(@Qualifier("SgsESqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
